//
//  ChartTrendView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 05.04.25.
//

import SwiftUI
import Charts

struct ChartTrendView: View {
    
    @Binding var trendTitle: String
    @Binding var averageTitle: String
    @Binding var totalAmount: Double
    @Binding var averageAmount: Double
    @Binding var data: [(day:String, amount:Double)]
    
    // 是否显示环比上个周期
    @State var showCompare = false
    
    private var gradient: Gradient {
        var colors = [Color.koiColorPrimary]
        colors.append(Color.koiColorPrimary.opacity(0.3))
        return Gradient(colors: colors)
    }
    
    var body: some View {
        VStack {
            HStack (spacing: 0) {
                Text(trendTitle)
                    .font(.system(size: 14))
                    .fontWeight(.medium)
                    .foregroundColor(Color.koiColorTitle)
                Spacer()
                Text(averageTitle)
                    .font(.system(size: 13))
                    .foregroundColor(Color.koiColorTitleSecond)
                Text(averageAmount.toAmountWithSign())
                    .font(.system(size: 13))
                    .foregroundColor(Color.koiColorTitle)
            }
            HStack(alignment:.bottom) {
                Text(totalAmount.toAmountWithSign())
                    .font(.system(size: 34))
                    .foregroundColor(Color.koiColorTitle)
                    .alignmentGuide(.bottom, computeValue: {_ in 35})
                if (showCompare) {
                    Text("较上周").foregroundColor(Color.koiColorChartUp)
                    Image("koi_ic_chart_up").alignmentGuide(.bottom, computeValue: {_ in 12})
                    Text("50%").foregroundColor(Color.koiColorChartUp)
                }
                Spacer()
            }
            Chart(data, id: \.day) {
                let amount = $0.amount
                LineMark(
                    x: .value("Date", $0.day),
                    y: .value("amount", $0.amount)
                )
                .foregroundStyle(Color.koiColorPrimary)
//                .foregroundStyle(gradient)
                .interpolationMethod(.catmullRom)
                PointMark(
                    x: .value("Day", $0.day),
                    y: .value("Value", $0.amount)
                )
                .symbolSize(20)
                .foregroundStyle(Color.red)
                .annotation(position:.top, content: {
                    if (amount >= averageAmount) {
                        Text(amount.toAmountWithSign())
                            .font(.system(size: 10))
                            .foregroundColor(Color.koiColorTitleSecond)
                    } else {
                        Text("")
                    }
                })
                // TODO 均线
                if averageAmount != 0 {
                    RuleMark(y: .value("Value", averageAmount))
                        .lineStyle(StrokeStyle(lineWidth: 1, dash: [5]))
                        .foregroundStyle(Color.red.opacity(0.5))
                }
            }
            .chartYAxis {
                // AxisMarks(values:.automatic(desiredCount:2))
            }
            .chartXAxis {
                AxisMarks(values: getXAxisValues()) { value in
                    AxisValueLabel(centered: true).font(.system(size: 8))
                }
            }
            .chartYScale(type: .linear)
            .frame(height: 112)
        }
        .padding(16)
        .background(Color.koiColorBackgroundItem)
        .cornerRadius(16)
    }
    
    private func getXAxisValues() -> [String] {
        let days = data.map{ $0.day }
        if (days.count > 12) {
            var values = [String]()
            var lastDayIndex = 0
            for dayIndex in stride(from: 0, to: days.count, by: 5) {
                values.append(days[dayIndex])
                lastDayIndex = dayIndex
            }
            if (lastDayIndex < days.count-1) {
                values.append(days.last!)
            }
            return values
        } else {
            return days
        }
    }
}

struct ChartTrendEntry: Equatable {
    let day: Date
    var amount: Int
    
    init(dayFormat: String, amount: Int) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        self.day = dateFormatter.date(from: dayFormat)!
        self.amount = amount
    }
}

@available(iOS 18.0, *)
#Preview {
    @Previewable @State var trendTitle = "支出趋势"
    @Previewable @State var averageTitle = "支出趋势"
    @Previewable @State var totalAmount = 0.0
    @Previewable @State var averageAmount = 0.0
    @Previewable @State var data = [
        (day: "2025-03-03", amount: 10.0),
        (day: "2025-03-04", amount: 20.0),
        (day: "2025-03-05", amount: 40.0),
        (day: "2025-03-06", amount: 30.0),
        (day: "2025-03-07", amount: 30.0),
        (day: "2025-03-08", amount: 10.0)
    ]
    ChartTrendView(
        trendTitle: $trendTitle,
        averageTitle: $averageTitle,
        totalAmount: $totalAmount,
        averageAmount: $averageAmount,
        data: $data)
}
